import java.util.PriorityQueue;

public class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();

    public MyTimer() {
        Thread t = new Thread(() -> {
            try {
                synchronized (locker) {
                    while (true) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask current = queue.peek();
                        if (current.getTime() > System.currentTimeMillis()) {
                            locker.wait(current.getTime() - System.currentTimeMillis());
                        } else {
                            current.run();
                            queue.poll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        });
        t.start();
    }

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            queue.offer(new MyTimerTask(runnable, delay));
            locker.notify();
        }
    }
}
